package com.kugou.miniapp.service;

import com.kugou.miniapp.dao.MailMapper;
import com.kugou.miniapp.dao.MailUserMapper;
import com.kugou.miniapp.dao.UserMapper;
import com.kugou.miniapp.domain.Mail;
import com.kugou.miniapp.domain.Music;
import com.kugou.miniapp.domain.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

@Service
public class MailService {

    @Autowired
    MusicService musicService;
    @Autowired(required = false)
    MailMapper mailMapper;
    @Autowired(required = false)
    MailUserMapper mailUserMapper;

    @Transactional
    public int sendMail(Mail mail) throws Exception {
        Date time = new Date();
        mail.setTime(time);
        int i = mailMapper.insertMail(mail);
        int mail_id = mail.getId();
        String from_user_id = mail.getFrom_user_id();
        Map<String, Object> mailUserFrom = new HashMap<>();
        mailUserFrom.put("mail_id", mail_id);
        mailUserFrom.put("user_id", from_user_id);
        int j = mailUserMapper.insert(mailUserFrom);
        Map<String, Object> mailUserTo = new HashMap<>();
        mailUserTo.put("mail_id", mail_id);
        mailUserTo.put("user_id", mail.getTo_user_id());
        int k = mailUserMapper.insert(mailUserTo);
        if (i+j+k!=3){
            throw new Exception("添加邮件插入失败");
        }
        return i+j+k;
    }

    public List<Mail> getMailsByUserId(String user_id){
        return mailMapper.getMailsByUserId(user_id);
    }

    public Integer delMailByMailId(String mail_id){
        return mailMapper.delMailsByMailId(mail_id);
    }

    public Integer deleteMailUserByMailIdAndUserId(String mail_id, String user_id){
        return mailUserMapper.deleteMailUserByMailIdAndUserId(mail_id, user_id);
    }



//    public List<Users> matchSimilarList(@RequestParam("userid") String userid){
//        //通过userid获取用户的music_list， 再获取其他用户以及他们的music_list
//        List<Music> musicList = musicService.getAllMusicByUserId(userid);
//        List<Users> users = userMapper.getUserAndMusicList();
//        //将自己的music_list和其他所有用户逐个对比他们的list并算出用户与用户之间的匹配度
//        for (Users u: users){
//            List<Music> other_music_list = u.getMusics();
//            for (Music o_m: other_music_list){
//                for (Music m: musicList){
//                    if (o_m.getMusic_id().equals(m.getMusic_id())){
//                        u.setSimilar(u.getSimilar()+1);
//                        break;
//                    }
//                }
//            }
//        }
//        //通过匹配度进行排序并返回
//        Collections.sort(users, new Comparator<Users>() {
//            @Override
//            public int compare(Users o1, Users o2) {
//                return o2.getSimilar()-o1.getSimilar();
//            }
//        });
//        return users;
//    }
}
